package com.cd.common.util;

import com.cd.common.domain.SysMenu;
import com.cd.common.domain.SysUser;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 导出excel
 **/
public class StatsReportExcelUtils {

    /**
     * @Description 教学演示
     * @Author lqq
     * @Date 2024/4/7 16:49
     **/
    public static void teachDemo(HttpServletResponse response){
        SXSSFWorkbook workbook = new SXSSFWorkbook();
        //创建工作表对象
        SXSSFSheet sheet = workbook.createSheet("sheet name");
        SXSSFRow row1 = sheet.createRow(0); //第一行
        SXSSFRow row2 = sheet.createRow(2); //第二行
        //第三行设置数据
        row2.createCell(0).setCellValue("教学演示");
        //判断类是否等于entry.getValue().getClass().equals(String.class)
        //合并1 2 行
        sheet.addMergedRegion(new CellRangeAddress(0,1,0,1));
        //遍历titles map设置表头信息
        //======================设置excel表头信息end======================
        try {
            //response.reset();
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码
            String urlEncoderFileName = URLEncoder.encode("lqqDemo", "UTF-8").replaceAll("\\+", "%20");
            response.addHeader("Content-disposition", "attachment;filename*=utf-8''" + urlEncoderFileName + ".xlsx");
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        //======================输出excel文件流end======================
    }

    public static void menuList(HttpServletResponse response,List<?> data ){
        SXSSFWorkbook workbook = new SXSSFWorkbook();
        //创建工作表对象
        SXSSFSheet sheet = workbook.createSheet("部门页");
        SXSSFSheet sheet2 = workbook.createSheet("空白页");
        SXSSFRow row1 = sheet.createRow(0); //第一行
        row1.createCell(0).setCellValue("菜单id");
        row1.createCell(1).setCellValue("菜单p_id");
        row1.createCell(2).setCellValue("菜单名称");

        SXSSFRow row2 = sheet.createRow(2); //第二行
        for (int i = 0; i < data.size(); i++) {
            SXSSFRow row = sheet.createRow(i + 1);
            SysMenu sysMenu = (SysMenu)data.get(i);
            row.createCell(0).setCellValue(sysMenu.getMenuId());
            row.createCell(1).setCellValue(sysMenu.getParentId());
            row.createCell(2).setCellValue(sysMenu.getMenuName());
        }
        //======================设置excel表头信息end======================
        try {
            //response.reset();
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码
            String urlEncoderFileName = URLEncoder.encode("lqqDemo", "UTF-8").replaceAll("\\+", "%20");
            response.addHeader("Content-disposition", "attachment;filename*=utf-8''" + urlEncoderFileName + ".xlsx");
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        //======================输出excel文件流end======================
    }

    public static  Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<String,Object>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);//不能获取到private属性，这里获得的是对应的属性 对象里面的值
            map.put(fieldName, value);
        }
        return map;
    }

    public static List<HashMap<String, Object>> listObjectToListMap(List<?> inputObjectList)  throws IllegalAccessException {
        List<HashMap<String, Object>> metaData = new ArrayList<>();
        for (Object object : inputObjectList) {
            metaData.add((HashMap<String, Object>) objectToMap(object));
        }
        return metaData;
    }
    /**
     * 该方法直接向浏览器输出excel文件
     * @param response http响应体对象
     * @param excelTitles 要设置的表头信息，在该方法中表头信息占2行
     * @param metaData 要写入表格的元数据
     * @param fileName 要保存的文件名
     */
    public static void export(HttpServletResponse response, Map<String, Object> excelTitles, List<HashMap<String, Object>> metaData, String fileName){
        SXSSFWorkbook workbook = new SXSSFWorkbook();
        //创建工作表对象
        SXSSFSheet sheet = workbook.createSheet();
        SXSSFRow row1 = sheet.createRow(0); //第一行
        SXSSFRow row2 = sheet.createRow(1); //第二行
        //遍历titles map设置表头信息
        Integer tempIndex = 0;
        for (Map.Entry<String, Object> entry : excelTitles.entrySet()) {
            if (entry.getValue().getClass().equals(String.class)) { //如果value是string类型则直接写入
                //从第1行到第2行合并
                sheet.addMergedRegion(new CellRangeAddress(0,1,tempIndex, tempIndex));//合并 首行尾行 首列尾列
                row1.createCell(tempIndex).setCellValue((String) entry.getValue());
                tempIndex++;
            }else { //如果不是string类型，又是一个map，则继续遍历
                Map<String, String> mapValue = (Map<String, String>) entry.getValue();
                //存在第0列,从第tempIndex列到第entry.size()+tempIndex-1列合并
                sheet.addMergedRegion(new CellRangeAddress(0,0,tempIndex, tempIndex+ mapValue.size()-1));
//                if ("month".equals(entry.getKey())) {
//                    row1.createCell(tempIndex).setCellValue("本月");
//                }else {
//                    row1.createCell(tempIndex).setCellValue("本年");
//                }
//                tempIndex=tempIndex+mapValue.size();
                for (Map.Entry<String, String> entry2 : mapValue.entrySet()) {
                    row2.createCell(tempIndex).setCellValue(entry2.getValue());
                    tempIndex++;
                }
            }
        }
        //======================设置excel表头信息end======================

        HashMap<String, Object> resultRow = null;
        SXSSFRow sheetRow = null;
        //一行一行的遍历result，每一行的resultRow.key正好与表头titles的key对应，取出相关的resultRow.value,就是对应的数据。然后写入单元格
        for (int i = 0; i < metaData.size(); i++) {
            resultRow = metaData.get(i);
            sheetRow = sheet.createRow(2 + i);
            tempIndex=0;
            for (Map.Entry<String, Object> entry : excelTitles.entrySet()) {
                if (entry.getValue().getClass().equals(String.class)) {
                    //如果是字符串，直接获取结果
                    sheetRow.createCell(tempIndex).setCellValue(resultRow.get(entry.getKey())+"");
                    tempIndex++;
                }else { //如果不是string类型，又是一个map，则继续遍历
                    Map<String, String> mapValue = (Map<String, String>) entry.getValue();
                    for (Map.Entry<String, String> entry2 : mapValue.entrySet()) {
                        String tempKey = entry.getKey()+entry2.getKey();
                        sheetRow.createCell(tempIndex).setCellValue(resultRow.get(tempKey)+"");
                        tempIndex++;
                    }
                }
            }
        }
        //======================写入excel元数据end======================

        try {
            //response.reset();
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码
            String urlEncoderFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.addHeader("Content-disposition", "attachment;filename*=utf-8''" + urlEncoderFileName + ".xlsx");
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        //======================输出excel文件流end======================
    }

    /**
     * @Description
     * @Author lqq
     * @Date 2024/4/3 14:48
     **/

    public static void exportSimple(HttpServletResponse response, Map<String, Object> excelTitles, List<SysUser> metaData, String fileName, String sheetName) throws IOException {
        SXSSFWorkbook workbook = new SXSSFWorkbook();
        SXSSFSheet sheet = workbook.createSheet(sheetName);
        SXSSFRow row1 = sheet.createRow(0);
        for (Map.Entry<String, Object> entry : excelTitles.entrySet()) {
            row1.createCell(0).setCellValue(entry.getValue()+"");
        }
    }
}
